import {
  ActionType,
  ModalForm,
  PageContainer,
  ProCard,
  ProColumns,
  ProFormDigit,
  ProFormSelect, ProFormText,
  ProTable, ProFormInstance
} from "@ant-design/pro-components";
import {Button, Col, Form, message, Popconfirm, Row, Tooltip} from "antd";
import {globalApi, globalLoadTableApi, handleGloblApi} from "@/services/admin-api/globalApi";
import {ArrowRightOutlined, CheckOutlined, CloseOutlined, LoginOutlined, SettingFilled} from "@ant-design/icons";
import React, {useEffect, useRef, useState} from "react";
import {
  citySelect,
  skillsToStr,
  toolsToStr,
  Worker,
  worker_skills,
  worker_tools,
  workerLevel,
  workerNation,
  workerSex,
  workerStatusEnum,
  workerType
} from "@/pages/Worker/Management";
import {DescriptionItem, Order} from "@/pages/Order/Management";
import '../../Order/Management/index.css'

export type OrderWorker = {
  owId: number
  owStatus: number
  owType: number
}

export const owType = [
  {label: '实习生', value: 0},
  {label: '收纳师', value: 1},
  {label: '副领队', value: 2},
  {label: '领队', value: 3},
]
export const owStatus = [
  {label: '待接单', value: 0},
  {label: '后台取消', value: 1},
  {label: '后台确认', value: 2},
  {label: '收纳拒绝', value: 3},
  {label: '收纳确认', value: 4},
  {label: '超时取消', value: 5},
]

export const owStatusEnum = {
  0: {text: '待接单', status: 'Warning'},
  1: {text: '后台取消', status: 'Error'},
  2: {text: '后台确认', status: 'Success'},
  3: {text: '收纳拒绝', status: 'Error'},
  4: {text: '收纳确认', status: 'Success'},
  5: {text: '超时取消', status: 'Error'},
}

const storeSelect = await globalApi('/store/select', {})

const urlParams = new URL(window.location.href).searchParams;
const orderId = Number(urlParams.get('orderId'));
console.log('urlParams = ', urlParams, ', orderId = ', orderId)

const orderData = await globalApi('/order/detail', {orderId})
const order = orderData.data
console.log('order = ', order)

export default () => {

  const actionRef = useRef<ActionType>();
  const actionDispatchRef = useRef<ActionType>();

  const [modalOpen, handleModalOpen] = useState(false)
  const [modalForceOpen, handleForceModalOpen] = useState(false)
  const [form] = Form.useForm()
  const [formForce] = Form.useForm()
  // const tableFormRef = useRef<ProFormInstance>();

  // const [order, setOrder] = useState<Order>()
  const [workerIds, setWorkerIds] = useState([])

  const columns: ProColumns<Worker & OrderWorker>[] = [
    {title: '排班ID', dataIndex: 'owId', valueType: 'digit'},
    {title: '服务人员ID', dataIndex: 'workerId', valueType: 'digit'},
    {title: '收纳编码', dataIndex: 'workerUuid', valueType: 'text'},
    {title: '昵称', dataIndex: 'workerNickName', valueType: 'text'},
    {title: '姓名', dataIndex: 'workerRealName', valueType: 'text'},
    {title: '电话', dataIndex: 'workerPhone', valueType: 'text'},
    {title: '类型', dataIndex: 'owType', valueType: 'select', fieldProps: {options: owType}},
    {title: '状态', dataIndex: 'owStatus', valueType: 'select', valueEnum: owStatusEnum},
    {title: '收纳类型', dataIndex: 'workerType', valueType: 'select', fieldProps: {options: workerType}},
    {title: '状态', dataIndex: 'workerStatus', valueType: 'select', valueEnum: workerStatusEnum},
    {title: '民族', dataIndex: 'workerNation', valueType: 'select', fieldProps: {options: workerNation}},
    {title: '性别', dataIndex: 'workerSex', valueType: 'select', fieldProps: {options: workerSex}},
    {title: '年龄', dataIndex: 'workerAge', valueType: 'digit'},
    {title: '地址', dataIndex: 'workerAddress', valueType: 'text', ellipsis: true},
    {title: '工龄', dataIndex: 'workerYear', valueType: 'digit'},
    {
      title: '技能',
      dataIndex: 'workerSkills',
      valueType: 'select',
      render: (_, record) => skillsToStr(record.workerSkills)
    },
    {
      title: '工具',
      dataIndex: 'workerTools',
      valueType: 'select',
      render: (_, record) => toolsToStr(record.workerTools)
    },
    {title: '等级', dataIndex: 'workerLevel', valueType: 'select', fieldProps: {options: workerLevel}},

    {title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '创建用户ID', dataIndex: 'createUserId', valueType: 'digit', hideInSearch: true,},
    {title: '创建用户', dataIndex: 'createUserName', valueType: 'text', hideInSearch: true,},
    {title: '更新时间', dataIndex: 'updateTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '更新用户ID', dataIndex: 'updateUserId', valueType: 'digit', hideInSearch: true,},
    {title: '更新用户', dataIndex: 'updateUserName', valueType: 'text', hideInSearch: true,},
    {
      title: <SettingFilled/>,
      render: (_, record) => [
        record.owStatus === 0 || record.owStatus === 2 || record.owStatus === 4 ?
          <Tooltip title={"取消"} key={`dispatch_cancel_${record.owId}`}>
            <Popconfirm
              title="取消排班"
              description={`确认取消 ${record.workerNickName} 的排班？${record.owStatus === 2 || record.owStatus == 4 ? '（警告）这条排班已经确认。' : ''}`}
              okText="Yes" cancelText="No"
              onConfirm={async () => {
                const r = await handleGloblApi('/dispatch/modify', {owId: record.owId, owStatus: 1})
                if (r) {
                  actionRef.current?.reload()
                }
              }}>
              <Button size="small" icon={<CloseOutlined/>} type="primary" danger/>
            </Popconfirm>
          </Tooltip> : '',
        record.owStatus === 0 ?
          <Tooltip title={"确认"} key={`dispatch_confirm_${record.owId}`}>
            <Popconfirm
              title="确认排班" description={`需要帮 ${record.workerNickName} 确认排班？`} okText="Yes" cancelText="No"
              onConfirm={async () => {
                const r = await handleGloblApi('/dispatch/modify', {owId: record.owId, owStatus: 2})
                if (r) {
                  actionRef.current?.reload()
                }
              }}>
              <Button size="small" icon={<CheckOutlined/>} type="primary"/>
            </Popconfirm>
          </Tooltip> : '',
        record.owStatus === 1 || record.owStatus === 3 || record.owStatus === 5 || record.owStatus === 6 || record.owStatus === 7 ?
          <Tooltip title={"派单"} key={`dispatch_confirm_${record.owId}`}>
            <Button
              size="small" icon={<ArrowRightOutlined/>} type="primary" onClick={async () => {
              handleModalOpen(true)
              form.setFieldsValue({workerId: record.workerId, owId: record.owId, owType: record.owType})
            }}></Button>
          </Tooltip> : '',
      ],
      valueType: 'option',
    },
  ];

  const columnsDispatch: ProColumns<Worker>[] = [
    {title: '服务人员ID', dataIndex: 'workerId', valueType: 'digit'},
    {title: '收纳编码', dataIndex: 'workerUuid', valueType: 'text'},
    {title: '昵称', dataIndex: 'workerNickName', valueType: 'text'},
    {title: '姓名', dataIndex: 'workerRealName', valueType: 'text'},
    {title: '手机', dataIndex: 'workerPhone', valueType: 'text'},
    {
      title: '工作日程',
      dataIndex: 'workTime',
      valueType: 'select',
      hideInTable: true,
      initialValue: 1,
      fieldProps: {options: [{label: '开启', value: 1}, {label: '关闭', value: 0}]}
    },
    {title: '类型', dataIndex: 'workerType', valueType: 'select', fieldProps: {options: workerType}},
    {title: '城市', dataIndex: 'workerCity', valueType: 'select', fieldProps: {options: citySelect.data}},
    {title: '状态', dataIndex: 'workerStatus', valueType: 'select', valueEnum: workerStatusEnum},
    {title: '民族', dataIndex: 'workerNation', valueType: 'select', fieldProps: {options: workerNation}},
    {
      title: '店铺',
      dataIndex: 'storeId',
      valueType: 'select',
      fieldProps: {options: storeSelect.data, showSearch: true},
      // initialValue: order.storeId,
    },
    {title: '性别', dataIndex: 'workerSex', valueType: 'select', fieldProps: {options: workerSex}},
    {title: '年龄', dataIndex: 'workerAge', valueType: 'digit', hideInSearch: true,},
    {title: '地址', dataIndex: 'workerAddress', valueType: 'text', ellipsis: true},
    {title: '工龄', dataIndex: 'workerYear', valueType: 'digit', hideInSearch: true,},
    {
      title: '技能',
      dataIndex: 'workerSkills',
      valueType: 'select',
      render: (_, record) => skillsToStr(record.workerSkills), fieldProps: {options: worker_skills.data}
    },
    {
      title: '工具',
      dataIndex: 'workerTools',
      valueType: 'select',
      render: (_, record) => toolsToStr(record.workerTools), fieldProps: {options: worker_tools.data}
    },
    {title: '等级', dataIndex: 'workerLevel', valueType: 'select', fieldProps: {options: workerLevel}},

    {title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '创建用户ID', dataIndex: 'createUserId', valueType: 'digit', hideInSearch: true,},
    {title: '创建用户', dataIndex: 'createUserName', valueType: 'text', hideInSearch: true,},
    {title: '更新时间', dataIndex: 'updateTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '更新用户ID', dataIndex: 'updateUserId', valueType: 'digit', hideInSearch: true,},
    {title: '更新用户', dataIndex: 'updateUserName', valueType: 'text', hideInSearch: true,},
    {
      title: <SettingFilled/>,
      render: (_, record) => [
        <Tooltip title={"指派"} key={`dispatchworker${record.workerId}`}>
          <Button
            size="small" icon={<ArrowRightOutlined/>} type="primary" onClick={() => {
            handleModalOpen(true)
            form.setFieldsValue({workerId: record.workerId})
          }}></Button>
        </Tooltip>,
      ],
      valueType: 'option',
    },
  ];

  // useEffect(() => {
  //   globalApi('/order/detail', {orderId})
  //     .then(data => {
  //       setOrder({...data.data})
  //       tableFormRef.current?.setFieldValue('storeId', data.data.storeId)
  //       tableFormRef.current?.submit()
  //     })
  // }, []);

  return <PageContainer header={{title: '', breadcrumb: {},}}>
    <ProCard split={'horizontal'} bordered headerBordered>
      <ProCard>
        <Row>
          <Col span={4}>
            <DescriptionItem title="订单ID" content={order?.orderId}/>
          </Col>
          <Col span={4}>
            <DescriptionItem title="服务时间" content={order?.serviceTime}/>
          </Col>
          <Col span={4}>
            <DescriptionItem title="起点" content={order?.startAddress}/>
          </Col>
          <Col span={4}>
            <DescriptionItem title="新家" content={order?.newAddress}/>
          </Col>
          <Col span={4}>
            <DescriptionItem title="距离(km)" content={order?.distance}/>
          </Col>
        </Row>
      </ProCard>
      <ProCard>
        <ProTable
          search={false} columns={columns} actionRef={actionRef} params={{orderId}} size={"small"}
          request={async (param) => {
            const r = await globalLoadTableApi('/dispatch/haveWorkertable', param)
            console.log('rrr = ', r.data)
            const workerIds = r.data.map((record: any) => record.workerId)
            setWorkerIds(workerIds)
            return r
          }}
          rowKey={(record) => record.owId}
          columnsState={{
            defaultValue: {
              createUserId: {show: false},
              updateUserId: {show: false},
            }
          }}/>
      </ProCard>
      <ProCard>
        <ProTable
          columns={columnsDispatch} actionRef={actionDispatchRef} params={{orderId, workerIds}} search={{span: 4}}
          request={async (param) => globalLoadTableApi('/dispatch/dispatchWorkertable', param)}
          rowKey={(record) => record.workerId} size={"small"}
          headerTitle={<>
            <Tooltip title={"强制派单，直接确认"}>
              <Button type={"primary"} icon={<LoginOutlined/>} onClick={() => {
                handleForceModalOpen(true)
              }}></Button>
            </Tooltip>
          </>}
          form={{initialValues: {storeId: order.storeId}}}
          // formRef={tableFormRef}
          columnsState={{
            defaultValue: {
              createUserId: {show: false},
              createUserName: {show: false},
              createTime: {show: false},
              updateUserId: {show: false},
              updateTime: {show: false},
              updateUserName: {show: false},
            }
          }}/>
      </ProCard>
    </ProCard>

    <ModalForm
      modalProps={{destroyOnClose: true}} submitTimeout={15000}
      width="400px" open={modalOpen} onOpenChange={handleModalOpen} form={form}
      onFinish={async (value) => {
        console.log('value = ', value);
        let success = await handleGloblApi('/dispatch/plan', value)

        if (success) {
          actionRef.current?.reload()
          actionDispatchRef.current?.reload()
          return true
        }

      }}
    >
      <ProFormDigit label="orderId" name="orderId" initialValue={orderId} hidden/>
      <ProFormDigit label="workerId" name="workerId" hidden/>
      <ProFormDigit label="owId" name="owId" hidden/>
      <ProFormSelect label="类型" rules={[{required: true}]} name="owType" options={owType}/>
    </ModalForm>

    <ModalForm
      modalProps={{destroyOnClose: true}} submitTimeout={15000}
      width="400px" open={modalForceOpen} onOpenChange={handleForceModalOpen} form={formForce}
      onFinish={async (value) => {
        console.log('value = ', value);
        let success = await handleGloblApi('/dispatch/forcePlan', value)

        if (success) {
          actionRef.current?.reload()
          actionDispatchRef.current?.reload()
          return true
        }

      }}
    >
      <ProFormDigit label="orderId" name="orderId" initialValue={orderId} hidden/>
      <ProFormText label={"服务人员手机"} name={"workerPhone"} rules={[{required: true}]}/>
      <ProFormSelect label="类型" rules={[{required: true}]} name="owType" options={owType}/>
    </ModalForm>

  </PageContainer>
}
